package be.music.tool.dao.template;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class XmlTemplate<T> {

	public void execute(String path, WriteFileCallback callback) {

		FileOutputStream stream = null;

		try {

			File file = new File(path);
			stream = FileUtils.openOutputStream(file);
			callback.write(stream);

		} catch (IOException e) {
			e.printStackTrace();
			// TODO: Throw persistence exception

		} finally {

			if (stream != null) {

				try {
					stream.close();
				} catch (IOException e) {
					e.printStackTrace();
					// TODO: Throw exception failed to close stream.
				}

			}

		}

	}

	@SuppressWarnings("unchecked")
	public T execute(String path, ReadFileCallback callback) {

		FileInputStream stream = null;
		T result = null;

		try {

			File file = new File(path);
			stream = FileUtils.openInputStream(file);
			result = (T) callback.load(stream);

		} catch (IOException e) {
			e.printStackTrace();
			// TODO: Throw persistence exception

		} finally {

			if (stream != null) {

				try {
					stream.close();
				} catch (IOException e) {
					e.printStackTrace();
					// TODO: Throw exception failed to close stream.
				}

			}

		}

		return result;

	}

}
